/**
 * Copyright ©2016-2022 tianyu education Corporation, All Rights Reserved
 * http://www.whty.com.cn/
 */
package profile.hujia.shiro.study.controller.config.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisCluster;

import java.io.*;
import java.util.Collection;

/**
 * class info
 *
 * @author hujia
 * @date 2019-12-11 13:53
 */
@Slf4j
public class RedisSessionDAO extends AbstractSessionDAO {

    private String prefix = "hujia_";

    @Autowired
    private JedisCluster jedisCluster;

    @Autowired
    private ObjectMapper jackson;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        assignSessionId(session, sessionId);
        save(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable serializable) {
        try {
            String key = serializable.toString();
            byte[] json = jedisCluster.get((prefix + key).getBytes());
            ByteArrayInputStream bais = new ByteArrayInputStream(json);
            ObjectInputStream ois = new ObjectInputStream(bais);
            SimpleSession simpleSession = (SimpleSession) ois.readObject();
            return simpleSession;
        } catch (Exception e) {
            log.error("error in jackson:" + e);
            return null;
        }
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        save(session);
    }

    @Override
    public void delete(Session session) {
        try {
            String key = jackson.writeValueAsString(session.getId());
            jedisCluster.del((prefix + key).getBytes());
        } catch (Exception e) {
            log.error("error in jackson:" + e);
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }

    private void save(Session session) {
        try {
            String key = session.getId().toString();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(session);
            jedisCluster.set((prefix + key).getBytes(), baos.toByteArray());
        } catch (Exception e) {
            log.error("error in jackson:" + e);
        }
    }
}